#include <buola/gui/containers/clayoutcontainer.h>

#include <buola/image/cfont.h>
#include <buola/image/cgc.h>
#include <buola/algorithm/container.h>
#include <buola/functors/predicates/unary.h>
#include <buola/widgets/cscrollbar.h>
#include <buola/iterator/indirect.h>

namespace buola { namespace gui {

CLayoutContainer::CLayoutContainer()
{
    SetBackColor(img::CColor(0.8,0.9,1.0));
}

CLayoutContainer::~CLayoutContainer()
{
}

void CLayoutContainer::Add(const PWindow &pWin,const CLayoutPos &pLeft,const CLayoutPos &pTop,
                                               const CLayoutPos &pRight,const CLayoutPos &pBottom)
{
    SLayout *lLayout=nullptr;
    
    for(const auto &l : mLayouts)
    {
        if(l->mWindow==pWin)
        {
            lLayout=l.get();
            break;
        }
    }
    
    if(!lLayout)
    {
        lLayout=&construct_back(mLayouts);
        lLayout->mWindow=pWin;
    }
    
    lLayout->mLeft=pLeft;
    lLayout->mTop=pTop;
    lLayout->mRight=pRight;
    lLayout->mBottom=pBottom;
    Manage(pWin);
}

void CLayoutContainer::OnLayout()
{
    for(const SLayout &l : indirect_range(mLayouts))
    {
        CRect_d lPos(l.mLeft.mAbs+l.mLeft.mRel*Size().x,
                     l.mTop.mAbs+l.mTop.mRel*Size().y,
                     l.mRight.mAbs+l.mRight.mRel*Size().x,
                     l.mBottom.mAbs+l.mBottom.mRel*Size().x);
        l.mWindow->Map(lPos);
    }
}

void CLayoutContainer::OnChildRemoved(const PWindow &pWindow)
{
    for(auto i=mLayouts.begin();i!=mLayouts.end();++i)
    {
        if(pWindow==(*i)->mWindow)
            mLayouts.erase(i);
    }
}

/*namespace gui*/ } /*namespace buola*/ }
